import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store";

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, resolve, reject) {
  if (resolve || reject)
    return originalPush.call(this, location, resolve, reject);
  return originalPush.call(this, location).catch((err) => err);
};

Vue.use(VueRouter);

// 路由映射数组
const routes = [
  {
    path: "/",
    redirect: "/home",
    component: () => import("@/views/layout"),
    children: [
      {
        path: "home",
        component: () => import("@/views/layout/home"),
      },
      {
        path: "qa",
        component: () => import("@/views/layout/qa"),
      },
      {
        path: "video",
        component: () => import("@/views/layout/video"),
      },
      {
        path: "my",
        component: () => import("@/views/layout/my"),
      },
    ],
  },
  {
    path: "/login",
    component: () => import("@/views/login"),
  },
  {
    path: "/user/collect",
    component: () => import("@/views/user/collect"),
    // 路由元信息（作用：给每个路由一些自定义数据）
    meta: {
      needLogin: true,
    },
  },
  {
    path: "/user/history",
    component: () => import("@/views/user/history"),
    // 路由元信息（作用：给每个路由一些自定义数据）
    meta: {
      needLogin: true,
    },
  },
  {
    path: "/search",
    component: () => import("@/views/search"),
  },
  {
    path: "/article/:id", // 动态路由   to="/article/id数据"
    component: () => import("@/views/article"),
  },
  {
    path: "/user/edit",
    component: () => import("@/views/user/edit"),
    meta: { needLogin: true },
  },
];
// 实例化路由对象
const router = new VueRouter({
  routes,
});
// router就是路由实例！
// 导航守卫（前置守卫）
router.beforeEach((to, from, next) => {
  console.log("任何的路由都走这里");
  console.log("to的信息是：", to); // to 要去哪里
  console.log("from的信息是：", from); // from 从哪里来
  // next 放行
  // 注意一定要next()，否则路由就会被挂起来，不会跳转界面
  // 需要登录才可以访问的界面的路由信息meta里面会有needLogin属性为true
  // 去的页面是否需要登录
  if (to.meta.needLogin) {
    // 去的界面需要登录,则要判断是否登录了
    if (store.getters.token) {
      // 登录了则放行
      next();
    } else {
      // 未登录则跳转到登录页去
      next("/login?url=" + to.path);
    }
  } else {
    // 去的界面不需要登录,则直接放行
    next();
  }
});

export default router;
